﻿/*============================================================================
  File:    Simple Sample AMO Datamining.cs

  Summary: Contains the code to build the Datamining Structure and Model of the sample

           Part of Simple Sample AMO Access

  Date:    November 2006
------------------------------------------------------------------------------
  This file is part of the Microsoft SQL Server Code Samples.

  Copyright (C) Microsoft Corporation.  All rights reserved.

  This source code is intended only as a supplement to Microsoft
  Development Tools and/or on-line documentation.  See these other
  materials for detailed information regarding Microsoft code samples.

  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/

#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.Sql;
using Microsoft.AnalysisServices;

#endregion

namespace Microsoft.Samples.SqlServer
{
    public partial class SimpleSampleAMOAccess
    {
        public void doDatamining()
        {
            Debug.WriteLine("starting... doDatamining()");
            Database db = svr.Databases[DatabaseName];

            //Start Data Mining Sample
            MiningStructure forecastingSalesStructure = CreateSalesForecastingMiningStructure(db);

            MiningModel forecastingSalesModel = CreateSalesForecastingMiningModel(forecastingSalesStructure);

            assignPermissionsSalesForecasting(db, forecastingSalesModel);
            Debug.WriteLine("ending... doDatamining()");
        }


        private static MiningStructure CreateSalesForecastingMiningStructure(Database db)
        {
            MiningStructure ms = db.MiningStructures.FindByName("Forecasting Sales Structure");
            if (ms != null)
                ms.Drop();
            ms = db.MiningStructures.Add("Forecasting Sales Structure", "Forecasting Sales Structure");
            ms.Source = new DataSourceViewBinding(db.DataSourceViews[0].ID);

            ScalarMiningStructureColumn amount = ms.Columns.Add("Amount", "Amount");
            amount.Type = MiningStructureColumnTypes.Double;
            amount.Content = MiningStructureColumnContents.Continuous;
            amount.KeyColumns.Add("vTimeSeries", "Amount", OleDbType.Currency);

            ScalarMiningStructureColumn modelRegion = ms.Columns.Add("Model Region", "Model Region");
            modelRegion.IsKey = true;
            modelRegion.Type = MiningStructureColumnTypes.Text;
            modelRegion.Content = MiningStructureColumnContents.Key;
            modelRegion.KeyColumns.Add("vTimeSeries", "ModelRegion", OleDbType.WChar, 56);

            ScalarMiningStructureColumn qty = ms.Columns.Add("Quantity", "Quantity");
            qty.Type = MiningStructureColumnTypes.Long;
            qty.Content = MiningStructureColumnContents.Continuous;
            qty.KeyColumns.Add("vTimeSeries", "Quantity", OleDbType.Integer);

            ScalarMiningStructureColumn timeIndex = ms.Columns.Add("TimeIndex", "TimeIndex");
            timeIndex.IsKey = true;
            timeIndex.Type = MiningStructureColumnTypes.Long;
            timeIndex.Content = MiningStructureColumnContents.KeyTime;
            timeIndex.KeyColumns.Add("vTimeSeries", "TimeIndex", OleDbType.Integer);

            ms.Update();
            return ms;
        }

        private static MiningModel CreateSalesForecastingMiningModel(MiningStructure ms)
        {
            if (ms.MiningModels.ContainsName("Sales Forecasting Model"))
            {
                ms.MiningModels["Sales Forecasting Model"].Drop();
            }
            MiningModel mm = ms.CreateMiningModel(true, "Sales Forecasting Model");
            mm.Algorithm = MiningModelAlgorithms.MicrosoftTimeSeries;
            mm.AlgorithmParameters.Add("PERIODICITY_HINT", "{12}");
            mm.AllowDrillThrough = true;

            mm.Columns["Model Region"].Usage = MiningModelColumnUsages.Key;
            mm.Columns["TimeIndex"].Usage = MiningModelColumnUsages.Key;
            mm.Columns["Amount"].Usage = MiningModelColumnUsages.Predict;
            mm.Columns.Remove("Quantity");
            mm.Update();
            mm.Process(ProcessType.ProcessFull);
            return mm;
        }

        private static void assignPermissionsSalesForecasting(Database db, MiningModel salesForecasting)
        {
            if( db.Roles.ContainsName("SalesMiningUsers"))
            {
                db.Roles["SalesMiningUsers"].Drop();
            }
            Role salesMiningUsers = db.Roles.Add("SalesMiningUsers", "SalesMiningUsers");
            salesMiningUsers.Members.Add(new RoleMember(@"Everyone"));
            salesMiningUsers.Update();

            MiningModelPermission salesMiningPermissions = new MiningModelPermission("SalesMiningUsers", "SalesMiningPermissions", "SalesMiningPermissions") ;
            salesMiningPermissions.AllowBrowsing = true;
            salesMiningPermissions.AllowDrillThrough = true;
            salesMiningPermissions.Read = ReadAccess.Allowed;
            salesMiningPermissions.ReadDefinition = ReadDefinitionAccess.Allowed;

            salesForecasting.MiningModelPermissions.Add(salesMiningPermissions);
            salesForecasting.Update();
        }

    }
}
